package com.yiwei.hdb.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.yiwei.hdb.R;
import com.yiwei.hdb.constant.Const;
import com.yiwei.hdb.event.IdcardZhiMaEvent;
import com.yiwei.hdb.event.OnVerifyEventMsg;
import com.yiwei.hdb.event.OnZhiMaEventMsg;
import com.yiwei.hdb.event.OnZhiMaVerifyEventMsg;
import com.yiwei.hdb.http.InfoCallBack;
import com.yiwei.hdb.impl.BankInfoImpl;
import com.yiwei.hdb.impl.ZhiMaInfoImpl;
import com.yiwei.hdb.model.BankModel;
import com.yiwei.hdb.model.ResponseModel;
import com.yiwei.hdb.model.ZhiMaCertModel;
import com.yiwei.hdb.model.ZhiMaModel;
import com.yiwei.hdb.util.ImageUtil;
import com.yiwei.hdb.util.PreferenceUtils;
import com.yiwei.hdb.util.RBLog;
import com.yiwei.hdb.util.ToastUtil;
import com.yiwei.hdb.util.Util;
import com.yiwei.hdb.view.CircularProgress;
import com.yiwei.hdb.view.Dialog;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 芝麻信用
 * Created by MasterDong on 16/8/11.
 */
public class NewZhiMaActivity extends BaseActivity implements View.OnClickListener {

    private EditText name, idcard;
    private CircularProgress loading;
    private ImageView mIv;
    private Bitmap bitmap;
    private TextView okBtn;

    private boolean isVerify;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseContentView(R.layout.activity_new_zhima);
        baseInitView(this, "AboutActivity", Const.ViewType.ACTIVITY);
        initView();
        EventBus.getDefault().register(this);
        PreferenceUtils.remove(this, "isfromAlipay");
        PreferenceUtils.remove(this, "zhima_biz_no");
    }


    private void initView() {
        setBackIntent();
        setTitleText("芝麻认证");
        mIv = (ImageView) findViewById(R.id.icon);
        bitmap = ImageUtil.readBitMap(this, R.mipmap.zhima);
        mIv.setImageBitmap(bitmap);
        loading = (CircularProgress) findViewById(R.id.progressBar);
        okBtn = (TextView) findViewById(R.id.ok);

        name = (EditText) findViewById(R.id.name);
        idcard = (EditText) findViewById(R.id.idcard);
        okBtn.setOnClickListener(this);


        name.setText(PreferenceUtils.getString(this, "zhima_name", ""));
        idcard.setText(PreferenceUtils.getString(this, "zhima_idno", ""));


//        checkAuthStatus();
    }

//    private void checkAuthStatus() {
//        //判断是否已认证
//        if (PreferenceUtils.getBoolean(this, "zhima_auth", false)) {
//            reAuthIDCardBtn.setVisibility(View.VISIBLE);
//            okBtn.setVisibility(View.VISIBLE);
//        }
//    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("ZhiMaFragment");
        getRealname();
        if (!TextUtils.isEmpty(PreferenceUtils.getString(this, "zhima_biz_no", ""))) {
            if (!PreferenceUtils.getBoolean(this, "isfromAlipay", false)) {
                getCertqueryInfo();
            }
        }
    }


    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("ZhiMaFragment");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ok:
                Util.getEventCount(this, "a_xyrz_qwsq");
                getZhiMaCertInfo();

                break;
        }
    }

    /**
     * 获取url和biz_no
     */
    private void getZhiMaCertInfo() {
        showLoading(true);
        new ZhiMaInfoImpl().getZhiMaCertInfo(this, Const.ZHI_MA_SCHEMA, new InfoCallBack() {
            @Override
            public void onSuccess(Object object) {
                showLoading(false);
                ZhiMaCertModel model = (ZhiMaCertModel) object;
                PreferenceUtils.putString(NewZhiMaActivity.this, "zhima_biz_no", model.getBiz_no());
//                ToastUtil.makeText(this, model.getUrl() + "  " + model.getBiz_no(), 1).show();

                doVerify(model.getUrl());
            }

            @Override
            public void onFailure(String cause) {
                showLoading(false);
                ToastUtil.makeText(NewZhiMaActivity.this, cause, Toast.LENGTH_SHORT);
            }
        });
    }


    /**
     * 启动支付宝进行认证
     *
     * @param url 开放平台返回的URL
     */
    private void doVerify(String url) {
        if (Util.isAppInstalled(this, "com.eg.android.AlipayGphone")) {
            Intent action = new Intent(Intent.ACTION_VIEW);
            StringBuilder builder = new StringBuilder();
            builder.append("alipays://platformapi/startapp?appId=20000067&url=");
            builder.append(URLEncoder.encode(url));
            action.setData(Uri.parse(builder.toString()));
            startActivity(action);
//            isVerify = true;
        } else {
            //处理没有安装支付宝的情况
            Dialog.showDefaultDialog(this, "", getString(R.string.download_alipay_tishi), getString(R.string.forget_it), getString(R.string.good), false, new Dialog.DialogDefaultClickListener() {
                @Override
                public void confirm() {
                    Intent action = new Intent(Intent.ACTION_VIEW);
                    action.setData(Uri.parse("https://m.alipay.com"));
                    startActivity(action);
                }

                @Override
                public void cancel() {

                }
            });
        }
    }

    /**
     * 获取认证结果查询
     */
    private void getCertqueryInfo() {
        showLoading(true);
        new ZhiMaInfoImpl().getZhiMaCertqueryInfo(this, PreferenceUtils.getString(this, "zhima_biz_no", ""), new InfoCallBack() {
            @Override
            public void onSuccess(Object object) {
                showLoading(false);
                ResponseModel model = (ResponseModel) object;

                ToastUtil.makeText(NewZhiMaActivity.this, model.getMsg(), Toast.LENGTH_SHORT);
                PreferenceUtils.remove(NewZhiMaActivity.this, "zhima_biz_no");
                sendEvent();
            }

            @Override
            public void onFailure(String cause) {
                showLoading(false);
                isVerify = false;
                ToastUtil.makeText(NewZhiMaActivity.this, cause, Toast.LENGTH_SHORT);
            }
        });
    }


    /**
     * 事件监听
     *
     * @param msg
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void OnZhiMaEventMsg(OnZhiMaEventMsg msg) {
        getCertqueryInfo();
    }

    /**
     * 是否显示加载框
     *
     * @param b
     */
    private void showLoading(boolean b) {
        if (b) {
            okBtn.setEnabled(false);
            if (loading != null) loading.setVisibility(View.VISIBLE);
        } else {
            okBtn.setEnabled(true);
            if (loading != null) loading.setVisibility(View.GONE);
        }
    }


    /**
     * 发送 页面跳转 事件
     */
    private void sendEvent() {
        EventBus.getDefault().post(new IdcardZhiMaEvent());
//        Intent intent = new Intent();
//        setResult(-1, intent);
        finish();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
            System.gc();
        }
        ImageUtil.releaseImageViewResouce(mIv);
        EventBus.getDefault().unregister(this);
    }

    /**
     * 获取用户姓名
     */
    private void getRealname() {
        showLoading(true);
        try {
            new BankInfoImpl().getBankRealname(this, new InfoCallBack() {
                @Override
                public void onSuccess(Object o) {
                    showLoading(false);
                    BankModel model = (BankModel) o;
                    name.setText(model.getMsg());
                    idcard.setText(model.getIdno());
                }

                @Override
                public void onFailure(String cause) {
                    ToastUtil.makeText(NewZhiMaActivity.this, cause, Toast.LENGTH_SHORT);
                    showLoading(false);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
